/*
 * Copyright © 2022-now 尛飛俠（Denvie） All rights reserved.
 */

package cn.denvie.springcloud.seata.order.service.impl;

import cn.denvie.springcloud.seata.common.model.constant.OrderStatus;
import cn.denvie.springcloud.seata.common.model.entity.Order;
import cn.denvie.springcloud.seata.common.model.vo.ResultVo;
import cn.denvie.springcloud.seata.order.feign.AccountFeignService;
import cn.denvie.springcloud.seata.order.feign.StorageFeignService;
import cn.denvie.springcloud.seata.order.mapper.OrderMapper;
import cn.denvie.springcloud.seata.order.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Order服务实现类。
 *
 * @author Denvie
 * @date 2022/4/08
 * @since 1.0.0
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    private AccountFeignService accountFeignService;
    @Autowired
    private StorageFeignService storageFeignService;

    @Override
    public Order booking(String userId, String commodityCode, int count, int money) {
        log.info("=============用户下单预订=================");
        return doBooking(userId, commodityCode, count, money);
    }

    //@Transactional(rollbackFor = Throwable.class)
    @GlobalTransactional(name = "OrderService.createOrder")
    @Override
    public Order purchase(String userId, String commodityCode, int count, int money) {
        log.info("=============用户下单采购=================");

        // 下单减库存
        Order order = doBooking(userId, commodityCode, count, money);

        // 支付订单
        pay(order.getId(), userId, money);
        order.setStatus(OrderStatus.SUCCESS.getValue());

        return order;
    }

    private Order doBooking(String userId, String commodityCode, int count, int money) {
        // 创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setCommodityCode(commodityCode);
        order.setCount(count);
        order.setMoney(money);
        order.setStatus(OrderStatus.INIT.getValue());
        boolean success = super.save(order);
        log.info("创建订单{}", success ? "成功" : "失败");

        // 扣减库存
        ResultVo deductResult = storageFeignService.deduct(commodityCode, count);
        if (deductResult.getCode() != ResultVo.SUCCESS_CODE) {
            throw new RuntimeException("扣减库存失败");
        }

        return order;
    }

    @Override
    public boolean pay(Long orderId, String userId, int money) {
        // 支付订单
        ResultVo debitResult = accountFeignService.debit(userId, money);
        log.info("订单【{}】支付{}，message：{}", orderId, debitResult.getCode() == ResultVo.SUCCESS_CODE ? "成功" : "失败",
                debitResult.getMessage());
        if (debitResult.getCode() != ResultVo.SUCCESS_CODE) {
            throw new RuntimeException("订单支付失败");
        }

        // 更新订单状态
        int count = getBaseMapper().updateOrderStatus(orderId, OrderStatus.SUCCESS.getValue());
        log.info("更新订单【{}】状态{}", orderId, count > 0 ? "成功" : "失败");

        return true;
    }
}
